package cn.zk.design.pub_sub;

import com.google.common.collect.Maps;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.utils.ZKPaths;

import java.util.List;
import java.util.Map;

/**
 * ClassName: Sub
 * Desc:
 * Date： 2016/12/7
 * Created：shaom
 */
public class Sub {

    public static final String connectString = "master:2181,slave01:2181,slave02:2181";
    public static final String path = "/Pub_Sub/db_config";
    static final Map<String, String> config = Maps.newHashMap();
    static CuratorFramework client = CuratorFrameworkFactory.builder().connectString(connectString)
            .sessionTimeoutMs(5000)
            .retryPolicy(new ExponentialBackoffRetry(2000, 5))
            .build();

    public static void main(String[] args) throws Exception {
        client.start();

        sub();

        Thread.sleep(Integer.MAX_VALUE);
    }

    private static void sub() throws Exception {

        List<String> children = client.getChildren().forPath(path);
        for (String child : children) {
            config.put(child, new String(client.getData().forPath(ZKPaths.makePath(path, child))));
        }
        System.out.println(config);

        PathChildrenCache cache = new PathChildrenCache(client, path, true);
        cache.start();
        cache.getListenable().addListener((client1, event) -> {
            switch (event.getType()) {
                case CHILD_UPDATED:
                    config.put(ZKPaths.getNodeFromPath(event.getData().getPath()), new String(event.getData().getData()));
                    System.out.println(config);
                    break;
                default:
                    break;
            }

        });

    }
}
